package com.forstudy.wiki.controller;

import com.forstudy.wiki.domain.Test;
import com.forstudy.wiki.service.TestService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class TestController {
    private static final Logger LOG = LoggerFactory.getLogger(TestController.class);

    @Autowired
    private TestService testService;

    /**
     * GET, POST, PUT, DELETE
     * <p>
     * /user?id=1
     * /user/1
     *
     * @return
     */
    // @PostMapping
    // @PutMapping
    // @DeleteMapping
    // @RequestMapping(value = "/user/1", method = RequestMethod.GET)
    // @RequestMapping(value = "/user/1", method = RequestMethod.DELETE)
    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public Map hello() {
        HashMap<String, Object> map = new HashMap<>();
        ArrayList<String> list = new ArrayList<>();
        list.add("123");
        map.put("test", list);
        map.keySet().forEach(key -> LOG.info("Key: " + key));
        return map;
    }


    @RequestMapping(value = "/hello1", method = RequestMethod.GET)
    public String hello1() {
        HashMap<String, Object> map = new HashMap<>();
        ArrayList<String> list = new ArrayList<>();
        list.add("123");
        map.put("test", list);
        LOG.info("list==>" + list.toString());
        map.keySet().forEach(key -> LOG.info("Key: " + key));
        return map.get("test").toString();
    }

    @PostMapping("/hello/post")
    public String helloPost(String name) {
        return "Hello World! Post，" + name;
    }

    @PostMapping("/hello/post1")
    public String helloPost1(@RequestBody User user) {
        return user.toString();
    }


    @Value("${test.hello}")
    private String customConfigHello;
    @Value("${test.default:defaultValue}") // 没有配置值，则使用默认值defaultValue
    private String customConfigHelloDefault;

    @GetMapping("/hello/readCustomConfig")
    public String readCustomConfig() {
        return customConfigHello.toString() + " " + customConfigHelloDefault.toString();
    }

    @RequestMapping("/test/list")
    public List<Test> testList() {
        LOG.warn("read custom config");
        return testService.list();
    }
}

class User {
    private String name;
    private Integer age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}